package org.hj.modules.generatecode.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.hj.common.annotation.AutoLog;
import org.hj.common.api.vo.Result;
import org.hj.common.system.query.QueryGenerator;
import org.hj.common.system.vo.LoginUser;

import org.hj.modules.generatecode.entity.ViewModule;
import org.hj.modules.generatecode.entity.ViewUiproperties;
import org.hj.modules.generatecode.service.IViewModuleService;
import java.util.Date;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;


import org.hj.modules.generatecode.service.IViewUipropertiesService;
import org.hj.modules.generatecode.util.DatabaseUtil;
import org.hj.modules.generatecode.vo.DatabaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
* @Description: 视图模板表
* @Author: gaobw
* @Date:   2020-06-16
* @Version: V1.0
*/
@Slf4j
@Api(tags="视图模板表")
@RestController
@RequestMapping("/generatecode/viewModule")
public class ViewModuleController {
   @Autowired
   private IViewModuleService viewModuleService;
    @Autowired
    private IViewUipropertiesService viewUipropertiesService;

   private DatabaseUtil databaseUtil;

   /**
     * 分页列表查询
    * @param viewModule
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "视图模板表-分页列表查询")
   @ApiOperation(value="视图模板表-分页列表查询", notes="视图模板表-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<ViewModule>> queryPageList(ViewModule viewModule,
                                     @RequestParam(name="searchParam") String searchParam,
                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                     HttpServletRequest req) {
       Result<IPage<ViewModule>> result = new Result<IPage<ViewModule>>();
       QueryWrapper<ViewModule> queryWrapper = QueryGenerator.initQueryWrapper(viewModule, req.getParameterMap());
       if(searchParam!=null&&!"".equals(searchParam)){
           queryWrapper.and(i->i.like("view_name",searchParam).or().like("view_comments",searchParam));
           //queryWrapper.like("view_name",searchParam).or().like("view_comments",searchParam);
       }
       Page<ViewModule> page = new Page<ViewModule>(pageNo, pageSize);
       IPage<ViewModule> pageList = viewModuleService.page(page, queryWrapper);
       result.setSuccess(true);
       result.setResult(pageList);
       return result;
   }

   /**
     *   添加
    * @param viewModule
    * @return
    */
   @AutoLog(value = "视图模板表-添加")
   @ApiOperation(value="视图模板表-添加", notes="视图模板表-添加")
   @PostMapping(value = "/add")
   @Transactional
   public Result<ViewModule> add(@RequestBody ViewModule viewModule) {
       Result<ViewModule> result = new Result<ViewModule>();
       LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
       try {
           /**
            * 保存主表的设置
            */
           viewModule.setViewCreateuser(sysUser.getId());
           viewModule.setViewCreatetime(new Date());
           viewModule.setViewDelFlag("0");
           viewModule.setViewUploadFlag("0");
           viewModuleService.save(viewModule);

           //将主表的每个字段进行处理，生成到viewUiproperties表
           List<DatabaseVO> columnNames = databaseUtil.getColumn(viewModule.getViewMaintable());
           for (int i = 0; i < columnNames.size(); i++) {
               DatabaseVO databaseVO = columnNames.get(i);
               viewUipropertiesService.saveColumn(viewModule.getId(),"0",databaseVO,i);
               databaseVO = null;
           }


           /**
            * 判断是否有明细表的数据，如果有，生成到viewUiproperties表
            */
           if(viewModule.getDetailedTable()!=null&&viewModule.getDetailedTable().length()>0){
               String[] ss=viewModule.getDetailedTable().split(",");
               for (String s:ss) {
                   List<DatabaseVO> cNs = databaseUtil.getColumn(s);
                   for (int i = 0; i < cNs.size(); i++) {
                       DatabaseVO databaseVO = cNs.get(i);
                       viewUipropertiesService.saveColumn(viewModule.getId(),"1",databaseVO,i);
                       databaseVO = null;
                   }
               }
           }

           result.success("添加成功！");
           result.setResult(viewModule);
       } catch (Exception e) {
           log.error(e.getMessage(),e);
           result.error500("操作失败");
       }
       return result;
   }

   /**
     *  编辑
    * @param viewModule
    * @return
    */
   @AutoLog(value = "视图模板表-编辑")
   @ApiOperation(value="视图模板表-编辑", notes="视图模板表-编辑")
   @PutMapping(value = "/edit")
   public Result<ViewModule> edit(@RequestBody ViewModule viewModule) {
       Result<ViewModule> result = new Result<ViewModule>();
       ViewModule viewModuleEntity = viewModuleService.getById(viewModule.getId());
       if(viewModuleEntity==null) {
           result.error500("未找到对应实体");
       }else {
           boolean ok = viewModuleService.updateById(viewModule);
           //TODO 返回false说明什么？
           if(ok) {
               result.success("修改成功!");
           }
       }

       return result;
   }


    /**
     *   通过id删除,逻辑删除
     * @param id
     * @return
     */
    @AutoLog(value = "视图模板表-通过id删除")
    @ApiOperation(value="视图模板表-通过id删除", notes="视图模板表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<ViewModule> delete(@RequestParam(name="id",required=true) String id) {
        Result<ViewModule> result = new Result<ViewModule>();
        ViewModule viewModule = viewModuleService.getById(id);
        if(viewModule==null) {
            result.error500("未找到对应实体");
        }else {
             viewModule.setViewDelFlag("1");
            boolean ok = viewModuleService.updateById(viewModule);
            if(ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }

   /**
     *   通过id删除,彻底删除，同时删除字段属性配置表
    * @param id
    * @return
    */
   @AutoLog(value = "视图模板表-通过id删除")
   @ApiOperation(value="视图模板表-通过id删除", notes="视图模板表-通过id删除")
   @DeleteMapping(value = "/thoroughDelete")
   public Result<ViewModule> thoroughDelete(@RequestParam(name="id",required=true) String id) {
       Result<ViewModule> result = new Result<ViewModule>();
       ViewModule viewModule = viewModuleService.getById(id);
       if(viewModule==null) {
           result.error500("未找到对应实体");
       }else {
           String tableName=viewModule.getViewMaintable();
           QueryWrapper<ViewUiproperties> wrapper=new QueryWrapper<>();
           wrapper.eq("ui_table",tableName);
           wrapper.eq("parent_id",id);
           viewUipropertiesService.remove(wrapper);
           boolean ok = viewModuleService.removeById(id);
           if(ok) {
               result.success("删除成功!");
           }
       }

       return result;
   }

   /**
     *  批量删除
    * @param ids
    * @return
    */
   @AutoLog(value = "视图模板表-批量删除")
   @ApiOperation(value="视图模板表-批量删除", notes="视图模板表-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<ViewModule> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       Result<ViewModule> result = new Result<ViewModule>();
       if(ids==null || "".equals(ids.trim())) {
           result.error500("参数不识别！");
       }else {
           this.viewModuleService.removeByIds(Arrays.asList(ids.split(",")));
           result.success("删除成功!");
       }
       return result;
   }

   /**
     * 通过id查询
    * @param id
    * @return
    */
   @AutoLog(value = "视图模板表-通过id查询")
   @ApiOperation(value="视图模板表-通过id查询", notes="视图模板表-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<ViewModule> queryById(@RequestParam(name="id",required=true) String id) {
       Result<ViewModule> result = new Result<ViewModule>();
       ViewModule viewModule = viewModuleService.getById(id);
       if(viewModule==null) {
           result.error500("未找到对应实体");
       }else {
           result.setResult(viewModule);
           result.setSuccess(true);
       }
       return result;
   }

/**
* 查询出数据库中的所有表
*/
@AutoLog(value = "视图模板表-查询出数据库中的所有表")
@ApiOperation(value="视图模板表-查询出数据库中的所有表", notes="视图模板表-查询出数据库中的所有表")
@GetMapping(value = "/querySQL")
public Result<?> querySQL() {
   Result result = new Result();
   List<String> tableNames = databaseUtil.getTableNames();
   result.setResult(tableNames);
   return result;
}

}
